#include "memberinfopage.h"
#include <QHeaderView>
#include <QMessageBox>
#include <QDebug>
#include <QApplication>

MemberInfoPage::MemberInfoPage(Database *db, QWidget *parent)
    : QWidget(parent), m_db(db), m_currentMemberId(-1)
{
    // 初始化服务层
    m_memberService = new MemberService(db);
    
    // 初始化UI组件指针
    m_mainLayout = nullptr;
    m_mainSplitter = nullptr;
    m_leftPanel = nullptr;
    m_rightPanel = nullptr;
    m_memberListGroup = nullptr;
    m_basicInfoGroup = nullptr;
    m_accountInfoGroup = nullptr;
    m_levelHistoryGroup = nullptr;
    m_memberTable = nullptr;
    m_levelHistoryTable = nullptr;
    m_searchEdit = nullptr;
    m_refreshBtn = nullptr;

    initUI();
    applyGreenThemeStyles();
    loadMemberList();
}

MemberInfoPage::~MemberInfoPage()
{
    delete m_memberService;
}

void MemberInfoPage::initUI()
{
    // 主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    m_mainLayout->setSpacing(10);

    // 创建分割器
    m_mainSplitter = new QSplitter(Qt::Horizontal, this);
    m_mainLayout->addWidget(m_mainSplitter);

    // 设置左右面板
    setupMemberListArea();
    setupMemberDetailArea();
    setupLevelHistoryArea();

    // 设置分割器比例
    m_mainSplitter->setSizes({400, 600});
    m_mainSplitter->setStretchFactor(0, 0);
    m_mainSplitter->setStretchFactor(1, 1);
}

void MemberInfoPage::setupMemberListArea()
{
    // 左侧面板
    m_leftPanel = new QWidget();
    m_leftLayout = new QVBoxLayout(m_leftPanel);
    m_leftLayout->setContentsMargins(5, 5, 5, 5);
    m_leftLayout->setSpacing(8);

    // 会员列表组
    m_memberListGroup = new QGroupBox("会员列表");
    m_leftLayout->addWidget(m_memberListGroup);

    QVBoxLayout *listLayout = new QVBoxLayout(m_memberListGroup);
    listLayout->setContentsMargins(10, 15, 10, 10);
    listLayout->setSpacing(8);

    // 搜索和刷新区域
    QHBoxLayout *searchLayout = new QHBoxLayout();
    m_searchEdit = new QLineEdit();
    m_searchEdit->setPlaceholderText("搜索会员姓名或手机号...");
    m_refreshBtn = new QPushButton("刷新");
    m_refreshBtn->setFixedWidth(60);
    
    searchLayout->addWidget(m_searchEdit);
    searchLayout->addWidget(m_refreshBtn);
    listLayout->addLayout(searchLayout);

    // 会员列表表格
    m_memberTable = new QTableWidget();
    m_memberTable->setColumnCount(4);
    QStringList headers = {"ID", "姓名", "手机号", "等级"};
    m_memberTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    m_memberTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_memberTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_memberTable->setAlternatingRowColors(true);
    m_memberTable->verticalHeader()->setVisible(false);
    
    // 设置列宽
    m_memberTable->setColumnWidth(0, 50);   // ID列
    m_memberTable->setColumnWidth(1, 80);   // 姓名列
    m_memberTable->setColumnWidth(2, 150);  // 手机号列 - 增加宽度以完整显示手机号
    m_memberTable->setColumnWidth(3, 80);   // 等级列
    
    listLayout->addWidget(m_memberTable);

    // 连接信号槽
    connect(m_memberTable, &QTableWidget::currentItemChanged, 
            this, &MemberInfoPage::onMemberSelectionChanged);
    connect(m_refreshBtn, &QPushButton::clicked, 
            this, &MemberInfoPage::onRefreshClicked);
    connect(m_searchEdit, &QLineEdit::textChanged, 
            this, &MemberInfoPage::onSearchTextChanged);

    m_mainSplitter->addWidget(m_leftPanel);
}

void MemberInfoPage::setupMemberDetailArea()
{
    // 右侧面板
    m_rightPanel = new QWidget();
    m_rightLayout = new QVBoxLayout(m_rightPanel);
    m_rightLayout->setContentsMargins(5, 5, 5, 5);
    m_rightLayout->setSpacing(10);

    // 基本信息组
    m_basicInfoGroup = new QGroupBox("会员基本信息");
    m_basicInfoLayout = new QGridLayout(m_basicInfoGroup);
    m_basicInfoLayout->setContentsMargins(15, 20, 15, 15);
    m_basicInfoLayout->setSpacing(10);

    // 创建标签
    int row = 0;
    m_basicInfoLayout->addWidget(new QLabel("会员ID:"), row, 0);
    m_memberIdLabel = new QLabel("未选择");
    m_basicInfoLayout->addWidget(m_memberIdLabel, row++, 1);

    m_basicInfoLayout->addWidget(new QLabel("姓名:"), row, 0);
    m_memberNameLabel = new QLabel("未选择");
    m_basicInfoLayout->addWidget(m_memberNameLabel, row++, 1);

    m_basicInfoLayout->addWidget(new QLabel("手机号:"), row, 0);
    m_memberPhoneLabel = new QLabel("未选择");
    m_basicInfoLayout->addWidget(m_memberPhoneLabel, row++, 1);

    m_basicInfoLayout->addWidget(new QLabel("会员等级:"), row, 0);
    m_memberLevelLabel = new QLabel("未选择");
    m_basicInfoLayout->addWidget(m_memberLevelLabel, row++, 1);

    m_basicInfoLayout->addWidget(new QLabel("折扣率:"), row, 0);
    m_discountRateLabel = new QLabel("未选择");
    m_basicInfoLayout->addWidget(m_discountRateLabel, row++, 1);

    m_basicInfoLayout->addWidget(new QLabel("注册时间:"), row, 0);
    m_registerTimeLabel = new QLabel("未选择");
    m_basicInfoLayout->addWidget(m_registerTimeLabel, row++, 1);

    m_rightLayout->addWidget(m_basicInfoGroup);

    // 账户信息组
    m_accountInfoGroup = new QGroupBox("账户信息");
    m_accountInfoLayout = new QGridLayout(m_accountInfoGroup);
    m_accountInfoLayout->setContentsMargins(15, 20, 15, 15);
    m_accountInfoLayout->setSpacing(10);

    row = 0;
    m_accountInfoLayout->addWidget(new QLabel("账户余额:"), row, 0);
    m_balanceLabel = new QLabel("未选择");
    m_accountInfoLayout->addWidget(m_balanceLabel, row++, 1);

    m_accountInfoLayout->addWidget(new QLabel("累计充值:"), row, 0);
    m_totalRechargedLabel = new QLabel("未选择");
    m_accountInfoLayout->addWidget(m_totalRechargedLabel, row++, 1);

    m_accountInfoLayout->addWidget(new QLabel("开户时间:"), row, 0);
    m_accountCreateTimeLabel = new QLabel("未选择");
    m_accountInfoLayout->addWidget(m_accountCreateTimeLabel, row++, 1);

    m_accountInfoLayout->addWidget(new QLabel("最后更新:"), row, 0);
    m_lastUpdateLabel = new QLabel("未选择");
    m_accountInfoLayout->addWidget(m_lastUpdateLabel, row++, 1);

    m_rightLayout->addWidget(m_accountInfoGroup);

    m_mainSplitter->addWidget(m_rightPanel);
}

void MemberInfoPage::setupLevelHistoryArea()
{
    // 等级历史组
    m_levelHistoryGroup = new QGroupBox("等级变更历史");
    m_levelHistoryLayout = new QVBoxLayout(m_levelHistoryGroup);
    m_levelHistoryLayout->setContentsMargins(15, 20, 15, 15);
    m_levelHistoryLayout->setSpacing(10);

    // 等级历史表格
    m_levelHistoryTable = new QTableWidget();
    m_levelHistoryTable->setColumnCount(5);
    QStringList historyHeaders = {"变更时间", "原等级", "新等级", "变更原因", "备注"};
    m_levelHistoryTable->setHorizontalHeaderLabels(historyHeaders);
    
    // 设置表格属性
    m_levelHistoryTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_levelHistoryTable->setAlternatingRowColors(true);
    m_levelHistoryTable->verticalHeader()->setVisible(false);
    m_levelHistoryTable->setMaximumHeight(200);
    
    // 设置列宽
    m_levelHistoryTable->setColumnWidth(0, 140);
    m_levelHistoryTable->setColumnWidth(1, 80);
    m_levelHistoryTable->setColumnWidth(2, 80);
    m_levelHistoryTable->setColumnWidth(3, 80);
    m_levelHistoryTable->setColumnWidth(4, 200);

    m_levelHistoryLayout->addWidget(m_levelHistoryTable);
    m_rightLayout->addWidget(m_levelHistoryGroup);
}

void MemberInfoPage::applyGreenThemeStyles()
{
    // 主窗口样式
    this->setStyleSheet(
        "QWidget {"
        "    background-color: #f8f9fa;"
        "    font-family: 'Microsoft YaHei', Arial, sans-serif;"
        "    font-size: 16px;"
        "}"
        
        // 分组框样式
        "QGroupBox {"
        "    font-size: 18px;"
        "    font-weight: bold;"
        "    color: #2d5a27;"
        "    border: 2px solid #4CAF50;"
        "    border-radius: 8px;"
        "    margin-top: 10px;"
        "    background-color: white;"
        "}"
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 15px;"
        "    padding: 0 8px 0 8px;"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    border-radius: 4px;"
        "    font-size: 18px;"
        "}"
        
        // 表格样式
        "QTableWidget {"
        "    background-color: white;"
        "    border: 1px solid #ddd;"
        "    border-radius: 6px;"
        "    gridline-color: #e0e0e0;"
        "    selection-background-color: #c8e6c9;"
        "    font-size: 16px;"
        "}"
        "QTableWidget::item {"
        "    padding: 8px;"
        "    border-bottom: 1px solid #f0f0f0;"
        "    font-size: 16px;"
        "}"
        "QTableWidget::item:selected {"
        "    background-color: #a5d6a7;"
        "    color: #1b5e20;"
        "    font-size: 16px;"
        "}"
        "QHeaderView::section {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    padding: 8px;"
        "    border: none;"
        "    font-weight: bold;"
        "    font-size: 16px;"
        "}"
        
        // 标签样式
        "QLabel {"
        "    color: #333;"
        "    font-size: 16px;"
        "}"
        
        // 按钮样式
        "QPushButton {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    border: none;"
        "    padding: 8px 16px;"
        "    border-radius: 4px;"
        "    font-weight: bold;"
        "    font-size: 16px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #45a049;"
        "    font-size: 16px;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #3d8b40;"
        "    font-size: 16px;"
        "}"
        
        // 输入框样式
        "QLineEdit {"
        "    border: 2px solid #ddd;"
        "    border-radius: 4px;"
        "    padding: 6px;"
        "    background-color: white;"
        "    font-size: 16px;"
        "}"
        "QLineEdit:focus {"
        "    border-color: #4CAF50;"
        "    font-size: 16px;"
        "}"
    );
}

void MemberInfoPage::loadMemberList()
{
    m_memberListData = m_memberService->getAllMembersForDisplay();
    
    m_memberTable->setRowCount(m_memberListData.size());
    
    for (int i = 0; i < m_memberListData.size(); ++i) {
        const auto &member = m_memberListData[i];
        
        m_memberTable->setItem(i, 0, new QTableWidgetItem(member["customer_id"].toString()));
        m_memberTable->setItem(i, 1, new QTableWidgetItem(member["name"].toString()));
        m_memberTable->setItem(i, 2, new QTableWidgetItem(member["phone"].toString()));
        m_memberTable->setItem(i, 3, new QTableWidgetItem(member["level_name"].toString()));
    }
}

void MemberInfoPage::loadMemberDetail(int memberId)
{
    QMap<QString, QVariant> memberInfo = m_memberService->getFormattedMemberInfo(memberId);
    
    if (memberInfo.isEmpty()) {
        clearMemberDetail();
        QMessageBox::warning(this, "错误", "无法获取会员信息");
        return;
    }

    // 更新基本信息
    m_memberIdLabel->setText(memberInfo["customer_id"].toString());
    m_memberNameLabel->setText(memberInfo["name"].toString());
    m_memberPhoneLabel->setText(memberInfo["phone"].toString());
    m_memberLevelLabel->setText(memberInfo["level_name"].toString());
    m_discountRateLabel->setText(memberInfo["discount_rate"].toString());
    m_registerTimeLabel->setText(memberInfo["register_time"].toString());

    // 更新账户信息
    m_balanceLabel->setText(memberInfo["balance"].toString());
    m_totalRechargedLabel->setText(memberInfo["total_recharged"].toString());
    m_accountCreateTimeLabel->setText(memberInfo["account_create_time"].toString());
    m_lastUpdateLabel->setText(memberInfo["last_update"].toString());

    // 加载等级历史
    loadMemberLevelHistory(memberId);
}

void MemberInfoPage::loadMemberLevelHistory(int memberId)
{
    QVector<QMap<QString, QVariant>> history = m_memberService->getMemberLevelHistory(memberId);
    
    m_levelHistoryTable->setRowCount(history.size());
    
    for (int i = 0; i < history.size(); ++i) {
        const auto &record = history[i];
        
        m_levelHistoryTable->setItem(i, 0, new QTableWidgetItem(record["change_time"].toString()));
        m_levelHistoryTable->setItem(i, 1, new QTableWidgetItem(record["old_level"].toString()));
        m_levelHistoryTable->setItem(i, 2, new QTableWidgetItem(record["new_level"].toString()));
        m_levelHistoryTable->setItem(i, 3, new QTableWidgetItem(record["change_reason"].toString()));
        m_levelHistoryTable->setItem(i, 4, new QTableWidgetItem(record["note"].toString()));
    }
}

void MemberInfoPage::clearMemberDetail()
{
    m_memberIdLabel->setText("未选择");
    m_memberNameLabel->setText("未选择");
    m_memberPhoneLabel->setText("未选择");
    m_memberLevelLabel->setText("未选择");
    m_discountRateLabel->setText("未选择");
    m_registerTimeLabel->setText("未选择");
    m_balanceLabel->setText("未选择");
    m_totalRechargedLabel->setText("未选择");
    m_accountCreateTimeLabel->setText("未选择");
    m_lastUpdateLabel->setText("未选择");
    
    m_levelHistoryTable->setRowCount(0);
}

void MemberInfoPage::filterMemberList(const QString &searchText)
{
    for (int i = 0; i < m_memberTable->rowCount(); ++i) {
        bool shouldShow = false;
        
        if (searchText.isEmpty()) {
            shouldShow = true;
        } else {
            // 搜索姓名和手机号
            QString name = m_memberTable->item(i, 1)->text();
            QString phone = m_memberTable->item(i, 2)->text();
            
            if (name.contains(searchText, Qt::CaseInsensitive) || 
                phone.contains(searchText, Qt::CaseInsensitive)) {
                shouldShow = true;
            }
        }
        
        m_memberTable->setRowHidden(i, !shouldShow);
    }
}

void MemberInfoPage::onMemberSelectionChanged(QTableWidgetItem *current, QTableWidgetItem *previous)
{
    Q_UNUSED(previous)
    
    if (current) {
        int currentRow = current->row();
        if (currentRow >= 0 && currentRow < m_memberListData.size()) {
            m_currentMemberId = m_memberListData[currentRow]["customer_id"].toInt();
            loadMemberDetail(m_currentMemberId);
        } else {
            m_currentMemberId = -1;
            clearMemberDetail();
        }
    } else {
        m_currentMemberId = -1;
        clearMemberDetail();
    }
}

void MemberInfoPage::onRefreshClicked()
{
    loadMemberList();
    clearMemberDetail();
    m_currentMemberId = -1;
    m_searchEdit->clear();
}

void MemberInfoPage::onSearchTextChanged()
{
    filterMemberList(m_searchEdit->text());
}